import collections


class Solution(object):
    def minimumSemesters(self, n, relations):
        """
        :type n: int
        :type relations: List[List[int]]
        :rtype: int
        """
        edges = collections.defaultdict(set)
        d = collections.defaultdict(int)
        for item in relations:
            edges[item[0]].add(item[1])
            if item[0] not in d:
                d[item[0]] = 0
            d[item[1]] += 1
        value = 0
        now_set = set()
        for key in d:
            if d[key] == 0:
                now_set.add(key)
        while now_set:
            value += 1
            next_set = set()
            for item in now_set:
                for next_item in edges[item]:
                    d[next_item] -= 1
                    if d[next_item] == 0:
                        next_set.add(next_item)
            now_set = next_set
        for key in d:
            if d[key] > 0:
                return - 1
        return value


data = Solution()
N = 4
relations = [[1, 2], [1, 3], [3, 2], [2, 4]]
print(data.minimumSemesters(N, relations))
